package com.moon.game.client;

import java.util.HashMap;
import java.util.Map;

import org.dom4j.Element;

import com.moon.game.config.GlobalConfig;
import com.moon.game.constants.GlobalConstants;
import com.moon.game.message.ObjMessage;

public class UdpClientSet {
	// DataServer
	private static int appServerSum = 1;
	private static Map<Integer, ClientPoolMulti> appClientPool = new HashMap<Integer, ClientPoolMulti>(); // Data

	/**
	 * 根据playerId散列数据服务器
	 * 
	 * @param playerId
	 * @return
	 */
	private static ClientPoolMulti getAppClient(String sid) {
		int index = Math.abs(sid.hashCode() % appServerSum);
		return appClientPool.get(index);
	}
	
	public static void init() {
		appServerSum = GlobalConfig.getAppServerSum();
		for (int i = 0; i < appServerSum; i++) {
			Element element = GlobalConfig.getAppServer(i);
			String bindip = element.attributeValue("host");
			int bindport = Integer.parseInt(element.attributeValue("http_port"));
			ClientPoolMulti udpClientMulti = new ClientPoolMulti(bindip, bindport, UdpClient.CODEC_PROTOBUF, GlobalConstants.DATA_SERVER_SEND_MAX, GlobalConstants.DATA_SERVER_REC_MAX, GlobalConstants.PROXY_CLIENT_SIZE);
			appClientPool.put(i, udpClientMulti);
		}
		
	}

	/**
	 * 发送请求给AppServer
	 * 
	 */
	public static void send2AppServer(ObjMessage data){
		UdpClientSet.getAppClient(data.getSid()).send(data);
	}
}
